# -*- coding: utf-8  -*-
#    Statistic Bot - A Free bot working on MediaWiki. In Arabic
#    Wikipedia, it works daily at 23:59 using cron.
#
#    Copyright (C) 2009 OsamaK
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#    Please report bugs or help imporving this program by connecting to
#    <OsamaK.WFM@gmail.com>
import wikipedia, okbot
import cPickle, datetime, time

class StatisticBot:
  def __init__(self):
    self.site = wikipedia.getSite(fam='wikipedia', code='ar') # although it can be used directly on other wikis, but this is the default opition.

  def run(self):
    todayDate = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%dT00:00:00Z") # Today date in MediaWiki format
    tomorrowDate = datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(days=1), "%Y-%m-%dT00:00:00Z") # Tomorrow date in MediaWiki format

    metaStat = self.getMetaStat()

    deletionStat = self.getDeletionStat(todayDate, tomorrowDate)
    protectionStat = self.getProtectionStat(todayDate, tomorrowDate)

    statInfo = metaStat; statInfo['deletions'] = deletionStat; statInfo['protections'] = protectionStat

    oldStatDiff = self.getOldStat(statInfo)
    self.saveStat(statInfo)

    formatedStat = self.formatStat(statInfo, oldStatDiff)

    self.putStat(formatedStat)

  def getMetaStat(self):
    print "Getting meta statistics"
    predata = {#api.php?action=query&meta=siteinfo&siprop=statistics&format=jsonfm
               'action': 'query',
               'meta': 'siteinfo',
               'siprop': 'statistics',
               'format': 'json',
                }
    
    while True:
      metaStat = okbot.getAPI(self.site, predata)
      if metaStat != None: break
    
    return metaStat['query']['statistics']

  def getDeletionStat(self, todayDate, tomorrowDate):
    print "Getting deletion statistics"
    predata = {#api.php?action=query&list=logevents&leprop=title&letype=delete&leend=2009-07-01T00:00:00Z&lestart=2009-07-02T00:00:00Z&lelimit=5000&format=jsonfm
               'action': 'query',
               'list': 'logevents',
               'leprop': 'title',
               'letype': 'delete',
               'leend': todayDate,
               'lestart': tomorrowDate,
               'lelimit': '5000',
               'format': 'json',
                }
    
    while True:
      deletionStat = okbot.getAPI(self.site, predata)
      if deletionStat != None: break

    try:
      return len(deletionStat['query']['logevents'])
    except KeyError:
      print deletionStat #for debugging
      raise KeyError

  def getProtectionStat(self, todayDate, tomorrowDate):
    print "Getting protection statistics"
    predata = {#api.php?action=query&list=logevents&leprop=title&letype=protect&leend=2009-07-01T00:00:00Z&lestart=2009-07-02T00:00:00Z&lelimit=5000&format=jsonfm
               'action': 'query',
               'list': 'logevents',
               'leprop': 'title',
               'letype': 'protect',
               'leend': todayDate,
               'lestart': tomorrowDate,
               'lelimit': '5000',
               'format': 'json',
                }
    
    while True:
      protectionStat = okbot.getAPI(self.site, predata)
      if protectionStat != None and 'query' in protectionStat: break

    return len(protectionStat['query']['logevents'])

  def getOldStat(self, statInfo):
    try:
      oldStatFile = cPickle.load(open('./statistic.db','r'))
      oldStatDiff = {
                     'oldPages': statInfo['pages'] - oldStatFile['pages'],
                     'oldArticles': statInfo['articles'] - oldStatFile['articles'],
                     'oldEdits': statInfo['edits'] - oldStatFile['edits'],
                     'oldUsers': statInfo['users'] - oldStatFile['users'],
                     'oldImages': statInfo['images'] - oldStatFile['images'],
                     'oldDeletions': statInfo['deletions'] - oldStatFile['deletions'],
                     'oldProtections': statInfo['protections'] - oldStatFile['protections'],
                     }
      return oldStatDiff
    except IOError:
      oldStatDiff = {
                     'oldPages': "",
                     'oldArticles': "",
                     'oldEdits': "",
                     'oldUsers': "",
                     'oldImages': "",
                     'oldDeletions': "",
                     'oldProtections': "",
                     }
      return oldStatDiff

  def saveStat(self, statInfo):
    cPickle.dump(statInfo, open('./statistic.db','w'))
      
  def formatStat(self, statInfo, oldStatDiff):
    statTemplate = u"""{{مستخدم:OsamaK/إحصاءات/قالب
|التاريخ={{subst:CURRENTTIME}}، {{subst:CURRENTDAY}} {{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}
|الصفحات = %(pages)s
|فرق الصفحات = %(oldPages)s
|المقالات = %(articles)s
|فرق المقالات = %(oldArticles)s
|التعديلات= %(edits)s
|فرق التعديلات = %(oldEdits)s
|المستخدمون= %(users)s
|فرق المستخدمين = %(oldUsers)s
|الصور = %(images)s
|فرق الصور = %(oldImages)s
|الحذف = %(deletions)s
|فرق الحذف = %(oldDeletions)s
|الحماية = %(protections)s
|فرق الحماية = %(oldProtections)s
}}"""

    statInfo.update(oldStatDiff)

    return statTemplate % statInfo

  def putStat(self, formatedStat):

    ArabicMonths = [u"يناير", u"فبراير", u"مارس", u"أبريل", u"مايو", u"يونيو", u"يوليو", u"أغسطس", u"سبتمبر", u"أكتوبر", u"نوفمبر", u"ديسمبر"]
    ArabicMonth = ArabicMonths[time.gmtime()[1] - 1] #Current Arabic month
    statTitle = u"مستخدم:OsamaK/إحصاءات/" + ArabicMonth + " " + str(time.gmtime()[0])
    statPage = wikipedia.Page(self.site, statTitle)
    try:
      statText = statPage.get()
    except wikipedia.NoPage:
      statText = ""
    if statText == "" or statText.find(u"<!---الجديد أعلاه--->") == -1:
      statText = u"{{مستخدم:OsamaK/إحصاءات/ترويسة}}\n\n{| class=\"wikitable\" style=\"width:90%\"\n|-\n! التاريخ (ت‌ع‌م)\n! الصفحات\n! المقالات\n! التعديلات\n! المستخدمون\n! الملفات\n! الحذف\n! الحماية\n<!---الجديد أعلاه--->\n|}"

    statText = statText.replace(u"<!---الجديد أعلاه--->", formatedStat + u"\n<!---الجديد أعلاه--->")

    okbot.put_page(self.site, statPage, statText, u"روبوت: إضافة إحصاء اليوم")

if __name__ == '__main__':
  try:
    bot = StatisticBot()
    bot.run()
  finally:
    wikipedia.stopme()
